<template>
  <div class="user-list-container">
    <el-card shadow="never">
      <template #header>
        <div class="table-header">
          <div class="left">
            <h3>用户列表</h3>
          </div>
          <div class="right">
            <el-button type="primary" @click="refresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名/邮箱">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="输入用户名或邮箱"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="角色">
          <el-select 
            v-model="searchForm.role" 
            placeholder="选择角色"
            clearable
          >
            <el-option label="普通用户" value="user" />
            <el-option label="VIP用户" value="vip" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="选择状态"
            clearable
          >
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 用户表格 -->
      <el-table
        :data="users"
        style="width: 100%"
        border
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column label="角色" width="100">
          <template #default="{row}">
            <el-tag :type="roleType[row.role]">
              {{ roleText[row.role] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="VIP状态" width="100">
          <template #default="{row}">
            <el-tag :type="row.isVIP ? 'success' : ''">
              {{ row.isVIP ? 'VIP' : '普通' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{row}">
            <el-tag :type="statusType[row.status]">
              {{ statusText[row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{row}">
            <el-button 
              size="small" 
              @click="viewDetail(row.id)"
            >
              详情
            </el-button>
            <el-dropdown @command="handleCommand($event, row.id)">
              <el-button size="small">
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="toggleStatus">
                    {{ row.status === 'active' ? '禁用' : '启用' }}
                  </el-dropdown-item>
                  <el-dropdown-item command="setAdmin" v-if="row.role !== 'admin'">
                    设为管理员
                  </el-dropdown-item>
                  <el-dropdown-item command="removeAdmin" v-if="row.role === 'admin'">
                    取消管理员
                  </el-dropdown-item>
                  <el-dropdown-item command="resetPassword" divided>
                    重置密码
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          @current-change="handlePageChange"
          layout="total, prev, pager, next"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUsers, updateUserStatus } from '@/api/admin'
import { Refresh, ArrowDown } from '@element-plus/icons-vue'

const router = useRouter()

// 角色文本映射
const roleText = {
  user: '普通用户',
  vip: 'VIP用户',
  admin: '管理员'
}

// 角色标签类型
const roleType = {
  user: '',
  vip: 'success',
  admin: 'danger'
}

// 状态文本映射
const statusText = {
  active: '正常',
  disabled: '禁用'
}

// 状态标签类型
const statusType = {
  active: 'success',
  disabled: 'danger'
}

// 搜索表单
const searchForm = ref({
  keyword: '',
  role: '',
  status: ''
})

// 分页
const pagination = ref({
  current: 1,
  size: 20,
  total: 0
})

// 数据
const users = ref([])
const loading = ref(false)

// 加载用户列表
const loadUsers = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm.value,
      page: pagination.value.current,
      size: pagination.value.size
    }
    
    const res = await getUsers(params)
    users.value = res.data.items
    pagination.value.total = res.data.total
  } catch (error) {
    console.error('加载用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  loadUsers()
}

// 刷新
const refresh = () => {
  loadUsers()
}

// 分页变化
const handlePageChange = () => {
  loadUsers()
}

// 查看详情
const viewDetail = (id) => {
  router.push(`/admin/users/detail/${id}`)
}

// 处理操作命令
const handleCommand = async (command, id) => {
  try {
    switch (command) {
      case 'toggleStatus':
        const user = users.value.find(u => u.id === id)
        const newStatus = user.status === 'active' ? 'disabled' : 'active'
        await updateUserStatus(id, { status: newStatus })
        ElMessage.success(`用户已${newStatus === 'active' ? '启用' : '禁用'}`)
        break
      case 'setAdmin':
        await updateUserStatus(id, { role: 'admin' })
        ElMessage.success('用户已设为管理员')
        break
      case 'removeAdmin':
        await updateUserStatus(id, { role: 'user' })
        ElMessage.success('已取消用户管理员权限')
        break
      case 'resetPassword':
        await ElMessageBox.confirm('确定重置此用户密码吗？', '警告', {
          type: 'warning'
        })
        // TODO: 调用重置密码API
        ElMessage.success('密码已重置')
        break
    }
    
    // 刷新列表
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error(error.message || '操作失败')
    }
  }
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>